package cn.apestar.common.huanxin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.apestar.common.DataContants;
import cn.apestar.common.config.Global;
import cn.apestar.common.exception.BaseException;
import cn.apestar.common.exception.ErrorCode;
import cn.apestar.common.utils.CacheUtils;
import cn.apestar.common.utils.ObjectUtils;

public class huanXinUtil {

	public static String getUrl(){
		return Global.getConfig("huanxin_url");
	}
	
	public static String getToken() throws ClientProtocolException, IOException{
		String clientId = Global.getConfig("huanxin_client_id");
		String clientSecret = Global.getConfig("huanxin_client_secret");
		String key = (String) CacheUtils.get("data", "huanxin");
		if(key == null){
			String token = getAppToken(clientId,clientSecret);
			Map map = JSON.parseObject(token, HashMap.class);
//			CacheKit.put("data", "huanxin", value)
			Long l = Long.parseLong(map.get("expires_in").toString()) + System.currentTimeMillis() - 10000;
			key = "Bearer " + map.get("access_token").toString();
			CacheUtils.put("data", "huanxin", key);
			CacheUtils.put("data", "huanxinTime", l);
		}else{
			Long l = (Long) CacheUtils.get("data", "huanxinTime");
			if( System.currentTimeMillis() >=l){
				CacheUtils.remove("data", "huanxin");
				getToken();
			}
		}
//		Map map = JSON.parseObject(token, HashMap.class);
		return key;
	}
	
	/**
	 * 获取APP管理员Token
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static String getAppToken(String client_id,String client_secret){
		JSONObject param = new JSONObject();
		param.put("grant_type", Global.getConfig("huanxin_grant_type"));
		param.put("client_id", client_id);
		param.put("client_secret", client_secret);
		try {
			return HttpUtil.ExecutionPost(getUrl()+"/token",param,null);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
	/**
	 * 注册IM用户[单个]
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @param username  当前用户
	 * @param newpassword  新密码
	 */
	public static boolean regUser(String username,String password,String nickname){
		Long longTome = System.currentTimeMillis();
		JSONObject param = new JSONObject();
		param.put("username", username);
		param.put("password", password);
		param.put("nickname", nickname);
		try {
			return HttpUtil.getResult(HttpUtil.ExecutionPost(getUrl()+"/users", param,getToken()));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
	/**
	 * 删除IM用户[单个]
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @param username 删除的用户
	 */
	public static boolean delUser(String username){
		try {
			return HttpUtil.getResult(HttpUtil.ExecutionDel(getUrl()+"/users/"+username,getToken()));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
	
	/**
	 * 重置IM用户密码
	 * @throws IOException 
	 * @throws ClientProtocolException 
 * 	 * @param username  当前用户
	 * @param newpassword  新密码
	 */
	public static boolean resetUserPassword(String username,String newpassword){
		JSONObject param = new JSONObject();
		param.put("newpassword", newpassword);
		try {
			return HttpUtil.getResult(HttpUtil.ExecutionPost(getUrl()+"/users/"+username+"/password", param,getToken()));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
	/**
	 * 给IM用户添加好友
	 * @param username  当前用户
	 * @param newUser  好友用户
	 */
	public static boolean addFriend(String username,String newUser){
		Map	map = new HashMap();
		try {
			return HttpUtil.getResult(HttpUtil.ExecutionPost(getUrl()+"/users/"+username+"/contacts/users/"+newUser, HttpUtil.getBasicNameValuePair(map),getToken()));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
	/**
	 * 删除用户添加好友
	 * @throws IOException 
	 * @throws ClientProtocolException
	 * @param username 当前用户
	 * @param newUser  好友用户
	 */
	public static void delFriend(String username,String newUser){
			final String username1 = username;
			//请求用户昵称
			final String newUser1 = newUser;
			Thread t = new Thread(new Runnable(){  
				public void run(){  
					try {
						//发送好友成功创建透传消息
						HttpUtil.getResult(HttpUtil.ExecutionDel(getUrl()+"/users/"+username1+"/contacts/users/"+newUser1,getToken()));
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						throw new BaseException(ErrorCode.error3,e.getMessage());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						throw new BaseException(ErrorCode.error3,e.getMessage());
					}
				}});  
			t.start();  
		
	}
	/**
	 * 发送消息到APP
	 * @param phone
	 * @return 
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static boolean transmissionMessageByone(String username,String message,String type,String messageType){
		JSONObject param2 = new JSONObject();
		if(!message.contains("code")){
			message = message ;
		}else{
//			param2.put("code", DataContants.ADD_FRI);
			Map mapResult = JSON.parseObject(message,HashMap.class);
			message = ObjectUtils.toString(mapResult.get("message"),"");
		}
		param2.put("code", messageType);
		JSONObject param = new JSONObject();
		param.put("target_type", "users");
		JSONArray list = new JSONArray();
		
		String[] s = username.split(",");
		for(int i = 0 ; i < s.length ; i++){
			Object o = s[i];
			if(o != null)
				list.add(o.toString().replaceAll("'", ""));
		}
		param.put("target", list);
		
		JSONObject param1 = new JSONObject();
		param1.put("type", type);
//		param1.put("action","action1");
		param1.put("msg",message);
		param.put("msg", param1);
		param.put("ext", param2);
//		param.put("from", "admin");
		try {
			return HttpUtil.getResult(HttpUtil.ExecutionPost(getUrl()+"/messages",param,getToken()));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new BaseException(ErrorCode.error3,e.getMessage());
		}
	}
	
}
